package com.example.spzx.Service.impl;

import com.example.exception.OmegaException;
import com.example.spzx.Mapper.SysMenuMapper;
import com.example.spzx.Service.SysMenuService;
import com.example.spzx.model.entity.system.SysMenu;
import com.example.spzx.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Resource
    private SysMenuMapper sysMenuMapper;
    public List<SysMenu> findNodes(){
        List<SysMenu> list=sysMenuMapper.selectAll();
        if(CollectionUtils.isEmpty(list)) return null;

        return convertlinetoTree(list, 0L);


    }
    public List<SysMenu> convertlinetoTree(List<SysMenu> datalist,Long pid){
        List<SysMenu> list=new ArrayList<>();

        for (SysMenu sysMenu:datalist){

            if(sysMenu.getParentId().equals(pid)){

                sysMenu.setChildren(convertlinetoTree(datalist, sysMenu.getId()));
            list.add(sysMenu);
            }
        }
        return list;

    }
    public    void add(SysMenu sysMenu){
        sysMenuMapper.add(sysMenu);

    }
    public void update(SysMenu sysMenu){
        sysMenuMapper.update(sysMenu);
    }
    public void delete(Long id){
        int count=sysMenuMapper.selectcountbyid(id);
        if(count>0){
            throw new OmegaException(ResultCodeEnum.NO_delete);

        }
        sysMenuMapper.deleteById(id);

    }
}
